package com.aiden.cashbook.charge

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.Rect
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.OrientationHelper
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.View
import com.aiden.cashbook.R
import com.aiden.cashbook.base.BaseFragment
import com.aiden.cashbook.base.BaseRecyclerViewAdapter
import com.aiden.cashbook.bean.Bill
import com.aiden.cashbook.bean.UseType
import com.aiden.cashbook.charge.dagger.DaggerChargeFragmentComponent
import com.aiden.cashbook.extension.*
import com.aiden.cashbook.utils.AlertDialogUtil
import com.aiden.cashbook.utils.DateUtils
import com.aiden.cashbook.utils.LogUtils
import kotlinx.android.synthetic.main.fragment_charge.*
import kotlinx.android.synthetic.main.layout_simple_button_item.view.*
import kotlinx.android.synthetic.main.layout_type_item.view.*
import javax.inject.Inject

@SuppressLint("SetTextI18n")
class ChargeFragment @Inject constructor() : BaseFragment(), ChargeContract.View {

    private lateinit var mTypeAdapter: BaseRecyclerViewAdapter<UseType>
    private lateinit var mKeyboardAdapter: BaseRecyclerViewAdapter<String>

    @Inject
    lateinit var mChargePresenter: ChargePresenter
    private lateinit var mType: String
    private var mTypeList = ArrayList<UseType>()
    private val mKeys = listOf("1", "2", "3", "<-", "4", "5", "6", "+", "7", "8", "9", "-", "C", "0", ".", "保存")
    private var mSelectPosition = 0
    private var mRemark = ""
    private var mDate = ""
    private var mNowInputNumber: StringBuilder = StringBuilder()

    override fun initView(): View {
        return mInflater.inflate(R.layout.fragment_charge, null)
    }

    override fun setListener() {
        btn_remark.setOnClickListener {
            AlertDialogUtil.EditDialog.show(activity!!, text = mRemark, hint = resources.getString(R.string.remark_hint),
                    onConfirmClickListener = object : AlertDialogUtil.EditDialog.OnConfirmClickListener {
                        override fun onConfirm(dialog: DialogInterface, input: String) {
                            mRemark = input
                        }
                    })
        }
        btn_date.setOnClickListener {
            AlertDialogUtil.date(activity!!, onDateSetListener = DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
                btn_date.text = "${year}年${month + 1}月${dayOfMonth}日"
                mDate = "$year-${DateUtils.simpleToDouble(year + 1)}-${DateUtils.simpleToDouble(dayOfMonth)}"
            })
        }
    }

    override fun initData() {

        DaggerChargeFragmentComponent.create().buildChargePresenterComponent().build().inject(this)

        initKeyboard()
        initTypeRecyclerView()
        mChargePresenter.takeView(this)
        mType = arguments!!.getString("type")
        mChargePresenter.accountType(mType)
    }

    private fun initTypeRecyclerView() {
        rv_type.layoutManager = GridLayoutManager(activity, 5, OrientationHelper.VERTICAL, false)
        mTypeAdapter = BaseRecyclerViewAdapter(activity!!, mTypeList, R.layout.layout_type_item) { view: View, useType: UseType, position: Int ->
            view.isSelected = mSelectPosition == position

            with(useType) {
                view.tv_type.text = name
                activity?.let { view.iv_type.display(it.getDrawableId(image)) }
                if (mSelectPosition == position) {
                    tv_type.text = name
                    activity?.let { iv_type.display(it.getDrawableId(image)) }
                }
                view.ll_content.measure(0, 0)
                view.ll_content.layoutParams.width = view.ll_content.measuredHeight
            }
        }
        mTypeAdapter.setOnItemClickListener(object : BaseRecyclerViewAdapter.OnItemClickListener {
            override fun onItemClick(v: View, position: Int) {
                if (position == mTypeList.size - 1) {
                    // TODO 新建类型
                } else {
                    val temp = mSelectPosition
                    mSelectPosition = position
                    mTypeAdapter.notifyItemChanged(mSelectPosition)
                    mTypeAdapter.notifyItemChanged(temp)
                }
            }
        })
        (rv_type.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false // 解决recyclerview刷新局部闪烁问题
        rv_type.adapter = mTypeAdapter
    }

    private fun initKeyboard() {
        rv_keyboard.layoutManager = GridLayoutManager(activity, 4)
        mKeyboardAdapter = BaseRecyclerViewAdapter(activity!!, mKeys, R.layout.layout_simple_button_item) { view: View, key: String, position: Int ->
            view.tv_item.text = key
        }
        mKeyboardAdapter.setOnItemClickListener(object : BaseRecyclerViewAdapter.OnItemClickListener {
            override fun onItemClick(v: View, position: Int) {
                val temp = tv_number.text.toString()
                val result = tv_calculate.text.toString()
                when (position) {
                    0, 1, 2, 4, 5, 6, 8, 9, 10 -> {
                        if (!TextUtils.isEmpty(result)) {
                            tv_calculate.text = result.plus(mKeys[position])
                        } else {
                            tv_number.text = temp.plus(mKeys[position])
                        }
                        mNowInputNumber.append(mKeys[position])
                        if (!TextUtils.isEmpty(result)) {
                            tv_number.text = calculate()
                        }
                    }
                    13 -> {
                        // 点击0
                        if (!TextUtils.isEmpty(temp)) {
                            if (TextUtils.isEmpty(result)) {
                                tv_number.text = temp.plus("0")
                            } else {
                                tv_calculate.text = result.plus("0")
                                // 计算
                                if (!TextUtils.isEmpty(result)) {
                                    tv_number.text = calculate()
                                }
                            }
                            mNowInputNumber.append("0")
                        }
                    }

                    3 -> {
                        // 退格
                        if (!TextUtils.isEmpty(result)) {
                            tv_calculate.text = result.substring(0, result.length - 1)
                            // 计算
                            tv_number.text = calculate()
                        } else {
                            if (!TextUtils.isEmpty(temp)) {
                                tv_number.text = temp.substring(0, temp.length - 1)
                            }
                        }
                        if (tv_number.text.toString() == "0.0") {
                            tv_number.text = ""
                            tv_calculate.text = ""
                        }
                    }

                    7, 11 -> {
                        if (!TextUtils.isEmpty(temp)) {
                            if (!TextUtils.isEmpty(result)) {
                                if (!result.endsWith("+") && !result.endsWith("-")) {
                                    tv_calculate.text = result.plus(mKeys[position])
                                    mNowInputNumber.delete(0, mNowInputNumber.length)
                                }
                            } else {
                                tv_calculate.text = temp.plus(mKeys[position])
                                mNowInputNumber.delete(0, mNowInputNumber.length)
                            }
                        }
                    }
                    12 -> {
                        if (!TextUtils.isEmpty(temp)) {
                            tv_number.text = ""
                        }
                        if (!TextUtils.isEmpty(result)) {
                            tv_calculate.text = ""
                        }
                        if (mNowInputNumber.isNotEmpty()) {
                            mNowInputNumber.delete(0, mNowInputNumber.length)
                        }
                    }
                    14 -> {
                        if (temp.isEmpty()) {
                            tv_number.text = "0."
                            mNowInputNumber.append("0.")
                        } else {
                            if (result.isEmpty()) {
                                if (!temp.contains(".")) {
                                    tv_number.text = temp.plus(".")
                                    mNowInputNumber.append(".")
                                }
                            } else {
                                if (mNowInputNumber.isEmpty()) {
                                    tv_calculate.text = result.plus("0.")
                                    mNowInputNumber.append("0.")
                                } else {
                                    val nowNumber = mNowInputNumber.toString()
                                    if (mNowInputNumber.indexOf(".") < 0) {
                                        tv_calculate.text = result.plus(".")
                                        mNowInputNumber.append(".")
                                    }
                                }
                            }
                        }
                    }
                    15 -> {
                        val number = tv_number.text.toString()
                        if (!TextUtils.isEmpty(number)) {
                            val bill = Bill(1L, mType, number.toDouble(), mTypeList[mSelectPosition].id, mDate, mRemark, "images", 0.0, 0.0, "location")
                            mChargePresenter.chargeAccount(bill)
                        }
                    }
                }
            }

        })
        rv_keyboard.adapter = mKeyboardAdapter
    }

    private fun calculate(): String {
        val cal = tv_calculate.text.toString()
        var result = 0.0
        val news = StringBuilder()
        var isAdd = false
        var isSub = false
        var tempResult = 0.0
        if (!TextUtils.isEmpty(cal)) {
            val list = cal.toCharArray()
            for (temp in list) {
                when (temp) {
                    '+' -> {
                        isAdd = true
                        isSub = false
                        tempResult = result
                        news.delete(0, news.length)
                    }
                    '-' -> {
                        isAdd = false
                        isSub = true
                        tempResult = result
                        news.delete(0, news.length)
                    }
                    else -> {
                        news.append(temp)
                        if (!isAdd && !isSub) {
                            result = java.lang.Double.valueOf(news.toString())
                        } else {
                            if (isAdd) {
                                result = tempResult + java.lang.Double.valueOf(news.toString())
                            }
                            if (isSub) {
                                result = tempResult - java.lang.Double.valueOf(news.toString())
                            }
                        }
                    }
                }
            }
        }
        return result.toString()
    }

    override fun saveSuccess() {
        activity?.toast("success")
        AlertDialogUtil.ConfirmDialog.show(activity!!, message = resources.getString(R.string.saved))
    }

    override fun saveFailure() {
        activity?.toast("failure")
    }

    override fun typeLoadSuccess(list: List<UseType>) {
        LogUtils.e("Charge", list.toString())
        with(mTypeList) {
            clear()
            addAll(list)
            mTypeList.add(UseType(null, "新建", "icon_zhichu_shouru_type_add", null, mType, false))
            mTypeAdapter.notifyDataSetChanged()
        }
    }

    override fun typeLoadFailure() {
        activity?.toast("type load failure")
    }
}